package cn.itcast.crm.service.impl;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ChuanJing
 * @date 2017年10月12日 上午3:13:55
 * @version 1.0
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	// 注入dao
	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	public List<Customer> findNoAssociationCustomers() {
		// fixedAreaId is null
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		// fixedAreaId is ?
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		// 解除关联动作
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		// 经过断点调试，发现action传递过来的customerIdStr有时是"null"
		if (StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)) {
			return;
		}
		
		// 切割字符串 1,2,3
		String[] customerIdArray = customerIdStr.split(",");
		for (String idStr : customerIdArray) {
			try {
				Integer id = Integer.parseInt(idStr);
				customerRepository.updateFixedAreaId(fixedAreaId, id);
			} catch (NumberFormatException e) {
				//e.printStackTrace();
				System.out.println("关联客户中，数字转换错误！！！");
			}
		}
	}

	@Override
	public Customer findByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}

	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone, password);
	}

	@Override
	public String findFixedAreaIdByAddress(String address) {
		return customerRepository.findFixedAreaIdByAddress(address);
	}
}